<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\WechatGroup;
use App\Models\WechatGroupUser;
use DB;
class WechatGroupUserController extends Controller
{
    protected $fields = [
        'uid' => 0,
        'gid' => 0,
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,$gid)
    {
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
			$uid = auth()->user()->id;
            $data['recordsTotal'] = User::join("wechat_group_users","wechat_group_users.uid","=","admin_users.id")
				->join("wechat_groups","wechat_group_users.gid","=","wechat_groups.id")
				->where(function ($query) use ($uid,$gid){
					$query->where("admin_users.pid",$uid)->where("wechat_groups.id",$gid);
				})->count();
				
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = User::join("wechat_group_users","wechat_group_users.uid","=","admin_users.id")
				->join("wechat_groups","wechat_group_users.gid","=","wechat_groups.id")
				->where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%');
                })->where(function ($query) use ($uid,$gid){
					$query->where("admin_users.pid",$uid)->where("wechat_groups.id",$gid);
				})->count();
				
                //$data['data'] = User::select(DB::raw('count(s_wechats.id) as wx_number,s_admin_users.name as username,s_wechat_groups.*'))
				$data['data'] = User::select(DB::raw('s_admin_users.*,s_wechat_group_users.id gid,(SELECT COUNT(*) FROM s_wechat_group_users WHERE uid=s_admin_users.id) group_number'))
					->join("wechat_group_users","wechat_group_users.uid","=","admin_users.id")
					->join("wechat_groups","wechat_group_users.gid","=","wechat_groups.id")
					->where(function ($query) use ($search) {
						$query->where('wechat_groups.name', 'LIKE', '%' . $search['value'] . '%');
					})
					->where(function ($query) use ($uid,$gid){
						$query->where("admin_users.pid",$uid)->where("wechat_groups.id",$gid);
					})
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
              /*   $data['recordsFiltered'] = User::join("wechat_group_users","wechat_group_users.uid","=","admin_users.id")
												->join("wechat_groups","wechat_group_users.gid","=","wechat_groups.id")
												->where(function ($query) use ($uid,$gid){
													$query->where("admin_users.pid",$uid)->where("wechat_groups.id",$gid);
												})->count(); */ 
				$data['recordsFiltered'] = $data['recordsTotal'];
												
                $data['data'] = User::select(DB::raw('s_admin_users.*,s_wechat_group_users.id gid,(SELECT COUNT(*) FROM s_wechat_group_users WHERE uid=s_admin_users.id) group_number'))
					->join("wechat_group_users","wechat_group_users.uid","=","admin_users.id")
					->join("wechat_groups","wechat_group_users.gid","=","wechat_groups.id")
					->where(function ($query) use ($uid,$gid){
						$query->where("admin_users.pid",$uid)->where("wechat_groups.id",$gid);
					})
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
			
            return response()->json($data);
        }
		$data['gid'] = $gid;
		$data['name'] = $this->getGroupName($gid);
        return view('admin.wechatgroupuser.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($gid)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
		$not_id = User::join('wechat_group_users','wechat_group_users.uid','=','admin_users.id')->where('pid',auth()->user()->id)->where('gid',$gid)->lists( 'admin_users.id');
		$data['userList'] = User::whereNotIn('id',$not_id)->where('pid',auth()->user()->id)->lists('name','id');
		$data['groupList'] = WechatGroup::where('uid',auth()->user()->id)->where('id',$gid)->get();
		$data['gid'] = $gid;
        return view('admin.wechatgroupuser.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		//$this->validate($request,['name'=>'required|unique:wechat_groups']);
		//if($this->validWechatGroup($request->get('name'),auth()->user()->id!=1?auth()->user()->id:$request->get('uid'))) return redirect('/admin/wechatgroup/create')->withErrors("已有该分组!");
        $wechatgroupser = new WechatGroupUser();
        foreach (array_keys($this->fields) as $field) {
			$wechatgroupser->$field = $request->get($field);
        }
		$wechatgroupser->save();
        return redirect('/admin/wechatgroupuser/'.$request->get('gid'))->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($gid)
    {
        $user = User::join('wechat_group_users','wechat_group_users.uid','=','admin_users.id')->where('gid',$gid)->lists( 'admin_users.name','admin_users.id');
		return response()->json($user);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
       $wechatgroupuser = WechatGroupUser::find((int)$id);
       if (!$wechatgroupuser) return redirect()->back()->withErrors("找不到该授权!");
       foreach (array_keys($this->fields) as $field) {
           $data[$field] = old($field, $wechatgroupuser->$field);
       }
	    $data['id'] = (int)$id;
		$gid= $wechatgroupuser->gid;
	    $not_id = User::join('wechat_group_users','wechat_group_users.uid','=','admin_users.id')->where('pid',auth()->user()->id)->where('uid','!=',$wechatgroupuser->uid)->where('gid',$gid)->lists( 'admin_users.id');
		$data['userList'] = User::whereNotIn('id',$not_id)->where('pid',auth()->user()->id)->lists('name','id');
		$data['groupList'] = WechatGroup::where('uid',auth()->user()->id)->where('id',$gid)->get();
		$data['gid'] = $gid;
       return view('admin.wechatgroupuser.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		//if($this->validWechatGroup($request->get('name'),auth()->user()->id!=1?auth()->user()->id:$request->get('uid'),$id)) return redirect('/admin/wechatgroup/'.$id.'/edit')->withErrors("已有该分组!");
        $wechatgroupuser = WechatGroupUser::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            $wechatgroupuser->$field = $request->get($field);
        }
        $wechatgroupuser->save();
        return redirect('/admin/wechatgroupuser/'.$request->get('gid'))->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag = WechatGroupUser::find((int)$id);
            if ($tag) {
                $tag->delete();
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }else{
            $idArr = explode(',',$id);
            $recordRow =WechatGroupUser::whereIn('id',$idArr)->delete();
            if(!$recordRow){
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }

	public function getUserName($id){
		$user = User::find((int)$id);
		return $user['name'];
	}
	public function getGroupName($id){
		$wechatgroup = WechatGroup::find((int)$id);
		return $wechatgroup['name'];
	}
	
}